<?php
/**
 * Created by PhpStorm.
 * User: mr_lee
 * Date: 2017/10/17
 * Time: 上午11:18
 */

namespace app\merchant\controller;


use app\common\model\Agent;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use think\Controller;
use Wechat\Wxobjopen;

class Micropay extends Controller
{
    public function index()
    {
        $request=request();
        $map['id'] = $request->get('id');
        $Merchant=new Merchant();
        $config = $Merchant->where($map)->find();
        if ($config['is_cartpay'] == 0) {
            $this->error('对不起商户不存在或没有开启刷卡支付权限');
        }
        $this->assign("headimg", $config['img']);
        $this->assign('shmc', $config['merchant']);
        $this->assign('merchid', $request->get('id'));

        $this->display();
    }

    public function send($id, $orderid)
    {
        $data = action('Index/sendtemplate', array($id, $orderid));

    }

    public function pay()
    {
        $request=request();
        $map['id'] = $request->post('merchid');
        $Merchant=new Merchant();
        $Agent=new Agent();
        $WxOpen=new WxOpen();
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users =$WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );

        $sh = $request->post('merchid');
        $weObj = new Wxobjopen($options);
        $price = $request->post('price');
        $appid = $agent['appid'];
        $mch_id = $agent['partnerid'];
        $out_trade_no = $this->getorder($sh);
        $body = "快捷支付";
        $sub_mch_id = $config['sub_mch_id'];
        $total_fee = $price * 100;
        $spbill_create_ip = $_SERVER["REMOTE_ADDR"];
        $nonce_str = $weObj->generateNonceStr();
        $auth_code = $request->post('auth_code');
        $arrdata = array("appid" => $appid, "mch_id" => $mch_id, "sub_mch_id" => $sub_mch_id, "nonce_str" => $nonce_str, "body" => $body, "out_trade_no" => $out_trade_no, "total_fee" => $total_fee, "spbill_create_ip" => $spbill_create_ip, "auth_code" => $auth_code);
        $pay_xml = $weObj->createmicroPackageXml($appid, $mch_id, $out_trade_no, $body, $sub_mch_id, $total_fee, $spbill_create_ip, $nonce_str, $auth_code);
        $pay_xml = $weObj->Mircopay_post($pay_xml);
        $data = $this->payzt($pay_xml, $sh);
        $data['orderid'] = $out_trade_no;
        $data['id'] = $request->post('merchid');


        echo json_encode($data);


    }

    public function payzt($pay_xml, $id)
    {
        if ($pay_xml['return_code'] == "SUCCESS") {
            if ($pay_xml['result_code'] == "FAIL") {

                $data['info'] = '支付失败1，原因：' . $pay_xml['err_code_des'];
                $data['code'] = $pay_xml['err_code'];

            } else {
                if ($pay_xml['trade_state'] && $pay_xml['trade_state'] != "SUCCESS") {
                    $data['info'] = '支付失败，原因：' . $pay_xml['trade_state_desc'];
                    $data['code'] = $pay_xml['trade_state'];
                } else {
                    $data['info'] = '支付成功';
                    $pays['mid'] = $id;
                    $pays['orderid'] = $pay_xml['out_trade_no'];
                    $pays['orderno'] = $pay_xml['transaction_id'];
                    $pays['pay_time'] = $pay_xml['time_end'];
                    $pays['add_time'] = time();
                    $pays['pay_statu'] = 1;
                    $pays['pay_fs'] = 2;
                    $pays['price'] = $pay_xml['total_fee'] / 100;
                    $pays['openid'] = $pay_xml['openid'];
                    $pays['payinfo'] = json_encode($pay_xml);
                    $Paylog=new Paylog();
                    $add = $Paylog->save($pays);
                    $sid=$Paylog->where(array('id'=>$add))->find();
                    action('Index/sendprint', array($sid));
                }

            }
        } elseif ($pay_xml['return_code'] == "FAIL") {

            $data['info'] = '支付失败2，原因：' . $pay_xml['return_msg'];

            $data['code'] = $pay_xml['err_code'];
        }

        return $data;


    }

    private function getorder($sh)
    {

        $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999) . rand(1, 10);
        session('orderid', $order);
        return $order;

    }

    public function orderquery($id, $orderid)
    {

        $Merchant=new Merchant();
        $Agent=new Agent();
        $WxOpen=new WxOpen();
        $map['id'] = $id;
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );
        $weObj = new Wxobjopen($options);
        $appid = $agent['appid'];
        $mch_id = $agent['partnerid'];
        $out_trade_no = $orderid;
        $sub_mch_id = $config['sub_mch_id'];
        $nonce_str = $weObj->generateNonceStr();
        $array = array($appid, $mch_id, $out_trade_no, $sub_mch_id, $nonce_str);
        $orderxml = $weObj->createOrderXml($appid, $mch_id, $sub_mch_id, $out_trade_no, $nonce_str);
        $orderxml2 = $weObj->getPayNum($orderxml);
        return $orderxml2;

    }

    public function getpaylog()
    {
        $request=request();
        if ($request->isAjax()) {
            $Paylog=new Paylog();
            $map['mid'] = $request->post('id');
            $map['is_statu'] = 1;
            $map['pay_fs'] = 2;
            $da1 = strtotime(date('Y-m-d'));
            $map['add_time'] = array('between', "" . $da1 . "," . time() . "");
            $data = $Paylog->where($map)->order('add_time desc')->select();
            $this->assign('list', $data);
            $this->display('paylog');

        }


    }

    public function checkpay()
    {
        $request=request();
        $orderid = $request->post('orderid');
        $id = $request->post('id');
        $payxml = $this->orderquery($id, $orderid);
//$payxml=$this->orderquery(I('post.id'),I('post.orderid'));
        $data = $this->payzt($payxml, $id);
        $data['orderid'] = $orderid;
        $data['id'] = $id;


        echo json_encode($data);


    }


}